package com.example.gobang.controller;

import com.example.gobang.mapper.UserMapper;
import com.example.gobang.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Description:
 * Date: 2024-09-04
 * Time: 10:53
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录  成功则返回用户并设置 session  失败则返回空对象
     * @param username
     * @param password
     * @param httpServletRequest
     * @return
     */
    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest httpServletRequest) {
        UserInfo userInfo = userMapper.selectByName(username);
        log.info("[login] username:{}",userInfo);
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            log.error("账号或密码不能为空");
            return new UserInfo();
        }
        if(userInfo == null) {
            log.error("用户不存在");
            return new UserInfo();
        }
        if(!password.equals(userInfo.getPassword())) {
            log.error("密码错误");
            return new UserInfo();
        }
        //密码正确的情况
        HttpSession httpSession = httpServletRequest.getSession(true);
        httpSession.setAttribute("userInfo",userInfo);
        return userInfo;
    }

    /**
     * 用户注册
     * 数据库的 user_name 字段设为 unique  如果插入重复的记录（即注册的用户名重复了） 那就会抛异常
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/register")
    public Object register(String username,String password) {
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserName(username);
            userInfo.setPassword(password);
            userMapper.insert(userInfo);
            return userInfo;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            return new UserInfo();
        }
    }

    /**
     * 从 session 里面获取用户信息
     * @return
     */
    @RequestMapping("/getUserInfo")
    public Object getUserInfo(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false); // 如果没获取到 session，不要创建新会话
            UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
            // 从数据库中拿到最新的用户信息
            UserInfo newUserInfo = userMapper.selectByName(userInfo.getUserName());
            return newUserInfo;
        } catch (NullPointerException e) {
            log.error("用户不存在");
            return new UserInfo();
        }
    }
}
